package org.uu.jwt;

import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Objects;

public class RSA256KeyUtil {

    // 数字签名
    public static final String KEY_ALGORITHM = "RSA";
    // 密钥长度
    public static final int KEY_SIZE = 1024;
    // 唯一的密钥实例
    private static volatile RSA256Key rsa256Key;

    public static RSA256Key generateRSA256Key() throws NoSuchAlgorithmException {
        if (Objects.isNull(rsa256Key)) {
            //RSA256Key单例的双重校验锁
            synchronized (RSA256Key.class) {
                //第二次校验：防止锁竞争中自旋的线程，拿到系统资源时，重复创建实例
                if (Objects.isNull(rsa256Key)) {
                    //密钥生成所需的随机数源
                    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
                    keyPairGen.initialize(KEY_SIZE);
                    //通过KeyPairGenerator生成密匙对KeyPair
                    KeyPair keyPair = keyPairGen.generateKeyPair();
                    //获取公钥和私钥
                    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
                    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

                    rsa256Key.setPrivateKey(privateKey);
                    rsa256Key.setPublicKey(publicKey);
                }
            }
        }
        return rsa256Key;
    }


}
